package com.ruoyi.web.controller.report;

import java.lang.reflect.Field;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.attached.service.IAttachedService;
import com.ruoyi.attachedData.domain.AttachedData;
import com.ruoyi.attachedData.service.IAttachedDataService;
import com.ruoyi.attachedRecord.domain.AttachedRecord;
import com.ruoyi.attachedRecord.service.IAttachedRecordService;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.report.domain.Report;
import com.ruoyi.sample.domain.Sample;
import com.ruoyi.sample.service.ISampleService;
import com.ruoyi.sampleRecord.domain.SampleRecord;
import com.ruoyi.sampleRecord.service.ISampleRecordService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.constant.DicConstants;
import com.ruoyi.report.service.IReportService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 检测报告Controller
 *
 * @author ruoyi
 * @date 2025-05-08
 */
@RestController
@RequestMapping("/report/report")
public class ReportController extends BaseController
{
    @Autowired
    private IReportService reportService;

    @Autowired
    private ISampleService sampleService;

    @Autowired
    private ISampleRecordService sampleRecordService;

    @Autowired
    private IAttachedDataService attachedDataService;

    @Autowired
    private IAttachedRecordService attachedRecordService;

    @Autowired
    private ISysUserService userService;
    /**
     * 查询检测报告列表
     */
    @PreAuthorize("@ss.hasPermi('report:report:list')")
    @GetMapping("/list")
    public TableDataInfo list(Report report)
    {

        //权限 项目经理和实验员 看被分配到的     业主和业主单位看自己单位的
        if(report.getIsRoleShow() != null && report.getIsRoleShow() == 1){
            Long userId = SecurityUtils.getLoginUser().getUserId();
            JSONObject jb = userService.getEngineeringIdsForUserId(userId);
            Long enterpriseId = (Long) jb.get("enterpriseId");
            List<Long> engineeringIds = (List<Long>) jb.get("engineeringIds");
            if(enterpriseId != 0){
                report.setEnterpriseId(enterpriseId);
            }else {
                //项目经理，实验员，劳务实验员
                if (!engineeringIds.isEmpty()) {
                    report.setIdsList(engineeringIds);
                } else {
                    List<Long> null_ids = new ArrayList<>();
                    null_ids.add(-1L);
                }
            }
        }

        startPage();
        List<Report> list = reportService.selectReportList(report);
        return getDataTable(list);
    }

    /**
     * 导出检测报告列表
     */
    @PreAuthorize("@ss.hasPermi('report:report:export')")
    @Log(title = "检测报告", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(Report report)
    {
        List<Report> list = reportService.selectReportList(report);

        ExcelUtil<Report> util = new ExcelUtil<Report>(Report.class);
        return util.exportExcel(list, "检测报告数据");
    }

    /**
     * 获取检测报告详细信息
     */
    @PreAuthorize("@ss.hasPermi('report:report:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        Report reportOne = reportService.selectReportById(id);
        if("shinei".equals(reportOne.getBusinessType()) ) {
            Sample sampleOne = sampleService.selectSampleById(reportOne.getSampleId());
            reportOne.setSampleOne(sampleOne);
            reportOne.setSampleNumber(sampleOne.getNumber());//总数量
            reportOne.setChargePerson(sampleOne.getTester());

            SampleRecord sampleRecord = new SampleRecord();
            sampleRecord.setSampleId(reportOne.getSampleId());
            List<SampleRecord> sampleRecordList = sampleRecordService.selectSampleRecordList(sampleRecord);
            reportOne.setSampleRecordList(sampleRecordList);
            Integer sum = 0;
            for (SampleRecord item: sampleRecordList){
                String sampleNumber = item.getSampleNumber();
                int sampleNumberNum = Integer.parseInt(sampleNumber);
                sum+=sampleNumberNum;
            }
            reportOne.setDoingSum(sum);
        }
        if("shiwai".equals(reportOne.getBusinessType())){
            Long attachedDataId = Long.parseLong(reportOne.getAttachedDataId());
            AttachedData attachedDataOne = attachedDataService.selectAttachedDataById(attachedDataId);
            reportOne.setAttachedDataOne(attachedDataOne);
            reportOne.setSampleNumber(attachedDataOne.getAmount());//总数
            reportOne.setChargePerson(attachedDataOne.getUserName()+"("+attachedDataOne.getNickName()+")");//人名

            AttachedRecord attachedRecord = new AttachedRecord();
            attachedRecord.setAttachedDataId(attachedDataId);
            List<AttachedRecord> attachedRecordList = attachedRecordService.selectAttachedRecordList(attachedRecord);
            reportOne.setAttachedRecordList(attachedRecordList);

            Integer sum2 = 0;
            for (AttachedRecord item: attachedRecordList){
                String test_number = item.getAmount();
                int testNumberNum = Integer.parseInt(test_number);
                sum2+=testNumberNum;
            }
            reportOne.setDoingSum(sum2);

        }

        return AjaxResult.success(reportOne);
    }

    /**
     * 新增检测报告
     */
    @PreAuthorize("@ss.hasPermi('report:report:add')")
    @Log(title = "检测报告", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Report report)
    {
        return toAjax(reportService.insertReport(report));
    }


    @PreAuthorize("@ss.hasPermi('report:report:add')")
    @PostMapping("/createReportNumber")
    public AjaxResult createReportNumber(@RequestBody Report report)
    {
        Long id = reportService.createReportNumber(report);
        Report one = reportService.selectReportById(id);
        return AjaxResult.success(one);
    }

    /**
     * 修改检测报告
     */
    @PreAuthorize("@ss.hasPermi('report:report:edit')")
    @Log(title = "检测报告", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Report report) throws ParseException {
        report.setUpdateType(DicConstants.BUSINESS_Manager.getCode());
        return toAjax(reportService.updateReport(report));
    }

    /**
     * 删除检测报告
     */
    @PreAuthorize("@ss.hasPermi('report:report:remove')")
    @Log(title = "检测报告", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(reportService.logicDeleteReport(ids,DicConstants.BUSINESS_Manager.getCode(),SecurityUtils.getUserId()));
    }
}
